<template>
	<n-menu :mode="mode" :value="activeKey" :collapsed="themeStore.sider.collapsed" :collapsed-width="64"
		:inverted="themeStore.darkMode" :collapsed-icon-size="22" :indent="18" :options="menus" :expanded-keys="expandedKeys"
		@update:value="handleUpdateMenu" @update:expanded-keys="handleUpdateExpandedKeys" />
</template>

<script setup lang="ts">
import { router } from "@/router";
import { useRouteStore, useThemeStore } from "@/store";
import { getActiveKeyPathsOfMenus, translateMenuLabel } from '@/utils';
import type { MenuOption } from "naive-ui";
import { RouteLocationRaw } from "vue-router";

const route = useRoute();
const themeStore = useThemeStore();
const routeStore = useRouteStore();

interface Props {
	/**菜单模式 */
	mode: "vertical" | "horizontal";
	/** 是否显示 */
	collapsed?: boolean;
	/**位置 */
	location?: string;
}

defineProps<Props>();

defineOptions({ name: "GlobalMenu" });

const activeKey = computed(() => (route.meta?.activeMenu ? route.meta.activeMenu : route.name) as string);

// const inverted = computed(() => themeStore.navTheme !== 'light' && !themeStore.darkMode)
const menus = computed(() => translateMenuLabel(routeStore.menus as App.GlobalMenuOption[]));

const expandedKeys = ref<string[]>([]);

/**
	 * 路由跳转
	 * @param to - 需要跳转的路由
	 * @param newTab - 是否在新的浏览器Tab标签打开
	 */
function routerPush(to: RouteLocationRaw, newTab = false) {
	if (newTab) {
		const routerData = router.resolve(to);
		window.open(routerData.href, '_blank');
		return Promise.resolve();
	}
	return router.push(to);
}

function handleUpdateMenu(_key: string, item: MenuOption) {
	const menuItem = item as App.GlobalMenuOption;
	routerPush(menuItem.routePath);
}

function handleUpdateExpandedKeys(keys: string[]) {
	expandedKeys.value = keys;
}

watch(
	() => route.name,
	() => {
		expandedKeys.value = getActiveKeyPathsOfMenus(activeKey.value, menus.value);
	},
	{ immediate: true }
);
</script>

<style scoped></style>
